package jane.mvc.controller;

import jane.mvc.actionresults.ContentResult;
import jane.mvc.actionresults.JsonResult;
import jane.mvc.actionresults.ViewResult;
import jane.mvc.actionresults.XMLResult;
import jane.mvc.engine.JaneMVCContext;
import jane.mvc.sessions.ISession;
import jane.mvc.sessions.ISessionFactory;
import jane.mvc.sessions.MemorySessionFactory;
import jane.mvc.utils.MyLog;
import jane.mvc.utils.Utils;

import java.util.HashMap;

import com.google.common.collect.Maps;

public abstract class Controller implements IController
{

	public HashMap<String, Object> ViewMap = Maps.newHashMap();
	private ISessionFactory _sessionFactory = null;
	public ISession session = null;
	private JaneMVCContext _context;

	public ISession getSession()
	{
		return session;
	}

	@Override
	public JaneMVCContext getContext()
	{
		return this._context;
	}

	@Override
	public void setContext(JaneMVCContext context)
	{

		this._context = context;
	}

	public void initController()
	{
		_sessionFactory = new MemorySessionFactory(this.getContext());
		session = _sessionFactory.getSession();
	}

	public JsonResult Json(Object obj)
	{
		return new JsonResult(obj);

	}

	public ViewResult View()
	{
		ViewResult viewResult = new ViewResult();

		// Gets the caller's class/method.
		String controllerClassName = Thread.currentThread().getStackTrace()[2]
				.getClassName();
		String methodName = Thread.currentThread().getStackTrace()[2]
				.getMethodName();

		viewResult.setViewFile(new Utils()
				.getDefaultViewFromControllerAndMethod(controllerClassName,
						methodName));

		MyLog.info(viewResult.getViewFile());

		return viewResult;
	}

	public ViewResult View(Object model)
	{
		ViewResult viewResult = new ViewResult(model);
		return viewResult;
	}

	public ContentResult Content(String content)
	{
		ContentResult contentResult = new ContentResult();
		contentResult.setContent(content);

		return contentResult;
	}

	public ContentResult Content(String content, String contentType)
	{

		ContentResult contentResult = new ContentResult();
		contentResult.setContent(content);
		contentResult.setContentType(contentType);

		return contentResult;
	}

	public XMLResult XML(Object content)
	{
		return new XMLResult(content);

	}
}
